package com.zhx.common.common.service;


import com.zhx.common.common.exception.BusinessException;
import com.zhx.common.common.exception.CommonErrorEnum;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Component
public class LockService {
    @Resource
    private RedissonClient redissonClient;

    public <T> T executeWithLock(String key, int expireTime, TimeUnit timeUnit, Supplier<T> supplier) {
        RLock lock = redissonClient.getLock(key);
        boolean success = false;
        try {
            success = lock.tryLock(expireTime, timeUnit);
            if(!success){
                throw new BusinessException(CommonErrorEnum.LOCK_LIMIT);
            }
            return supplier.get();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }

    public <T> T executeWithLock(String key,  Supplier<T> supplier){
        return executeWithLock(key, -1,TimeUnit.MICROSECONDS, supplier);
    }

    public <T> T executeWithLock(String key,  Runnable runnable) {
        return executeWithLock(key, -1, TimeUnit.MICROSECONDS, () -> {
            runnable.run();
            return null;
        });
    }

    @FunctionalInterface
    public interface Supplier<T> {

        /**
         * Gets a result.
         *
         * @return a result
         */
        T get() throws Throwable;
    }
}
